package com.example.controller;

import com.example.entity.Course;
import com.example.service.CourseService;
import com.example.service.JSMindService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author： wzz
 * @date： 2021-10-28 22:31
 */
@Slf4j
@Controller
@RequestMapping(value = "/video")
public class VideoController {

    @Autowired
    private CourseService courseService;
    @Resource
    private JSMindService jsMindService;

    private final static String utf8 ="utf-8";
    private final  static String path = "/opt/video";
    private final  static String filepath = "/opt/word";


//    视频上传
    @RequestMapping("/upload/{book_name}/{menu_topic}")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response,
                       @PathVariable(value = "book_name") String book_name,
                       @PathVariable(value = "menu_topic") String menu_topic) throws Exception {

        //分片

            if (request instanceof MultipartHttpServletRequest) {
                System.out.println("error");
            }


        response.setCharacterEncoding(utf8);
        Integer schunk = null;
        Integer schunks = null;
        String name = null;
        String lastModifiedDate = null;
        String uploadPath = System.getProperty("user.dir")+"/static"+path;
        System.out.println("uploadPath==="+uploadPath);
        BufferedOutputStream os = null;
        try{
//            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024);
            factory.setRepository(new File(uploadPath));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(5L *1024L *1024L* 1024L);
            upload.setSizeMax(10L *1024L *1024L*1024L);
            List<FileItem> items = upload.parseRequest(request);

            for(FileItem item : items){
                if(item.isFormField()){
//                    分片数
                    if("chunk".equals(item.getFieldName())){
                        schunk = Integer.parseInt(item.getString(utf8));
                    }
//                    总分片数
                    if("chunks".equals(item.getFieldName())){
                        schunks = Integer.parseInt(item.getString(utf8));
                    }
//                    文件名：根据时间戳命名,恰好文件存储了存进去的时间
                    if("name".equals(item.getFieldName())){
                        name = item.getString(utf8);
                    }

                    if ("lastModifiedDate".equals(item.getFieldName())){
                        lastModifiedDate = item.getString(utf8);
                    }
                }
            }
            for(FileItem item : items){
                if(!item.isFormField()){
                    String temFileName = name;   //未分片的话文件名就是原名
                    //未分片的话文件名规定为时间戳
//                    int i=name.lastIndexOf(".");
//                    String temFileName = lastModifiedDate +name.substring(i);
                    System.out.println(temFileName);
                    if(name != null){   //文件名不能为空
                        if(schunk != null){   //分片数目
                            temFileName = schunk +"_"+name;   //分片的话文件名就是这个
                        }
                        File temFile = new File(uploadPath,temFileName);
                        if(!temFile.exists()){//断点续传
                            item.write(temFile);
                        }
                    }
                }
            }
            //文件合并
            if(schunk != null && schunk.intValue() == schunks.intValue()-1){
                File tempFile = new File(uploadPath,name);
                os = new BufferedOutputStream(new FileOutputStream(tempFile));

                for(int i=0 ;i<schunks;i++){
                    File file = new File(uploadPath,i+"_"+name);
                    while(!file.exists()){
                        Thread.sleep(100);
                    }
                    byte[] bytes = FileUtils.readFileToByteArray(file);
                    os.write(bytes);
                    os.flush();
                    file.delete();
                }
                os.flush();
            }

            //上传成功后将视频的路径存储在数据库中
//            int i=name.lastIndexOf(".");
            String videoPath = path+'/'+name;
            List<Course> courseList = courseService.selectTrue(book_name,menu_topic);
            int j = 0;
            if ( courseList.size()!=0){
                j = courseService.updateCourse(book_name,menu_topic,videoPath,null);
            }else {
                j = courseService.insertVideo(book_name,menu_topic,videoPath);
            }

            log.info("插入情况："+j);
            jsMindService.updateContent(book_name,menu_topic.split(":")[1]);
            response.getWriter().write("上传成功"+name);
        }finally {
            try{
                if(os != null){
                    os.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }


//    文件上传
    @RequestMapping("/fileUpload/{book_name}/{menu_topic}")
    @ResponseBody
    public void fileUpload(HttpServletRequest request, HttpServletResponse response,
                       @PathVariable(value = "book_name") String book_name,
                       @PathVariable(value = "menu_topic") String menu_topic) throws Exception {

        //分片
        response.setCharacterEncoding(utf8);
        Integer schunk = null;
        Integer schunks = null;
        String name = null;
        String lastModifiedDate = null;
        String uploadPath = System.getProperty("user.dir")+"/static"+filepath;
        System.out.println("uploadPath==="+uploadPath);
        BufferedOutputStream os = null;
        try{
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024);
            factory.setRepository(new File(uploadPath));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(5l *1024l *1024l*1024l);
            upload.setSizeMax(10l *1024l *1024l*1024l);
            List<FileItem> items = upload.parseRequest(request);

            for(FileItem item : items){
                if(item.isFormField()){
//                    分片数
                    if("chunk".equals(item.getFieldName())){
                        schunk = Integer.parseInt(item.getString(utf8));
                    }
//                    总分片数
                    if("chunks".equals(item.getFieldName())){
                        schunks = Integer.parseInt(item.getString(utf8));
                    }
//                    文件名：根据时间戳命名,恰好文件存储了存进去的时间
                    if("name".equals(item.getFieldName())){
                        name = item.getString(utf8);

                    }
                    if ("lastModifiedDate".equals(item.getFieldName())){
                        lastModifiedDate = item.getString(utf8);
                    }
                }
            }
            for(FileItem item : items){
                if(!item.isFormField()){
//                    String temFileName = name;   //未分片的话文件名就是原名
                    //未分片的话文件名规定为时间戳
                    int i=name.lastIndexOf(".");
                    String temFileName = lastModifiedDate +name.substring(i);
                    System.out.println(temFileName);
                    if(name != null){   //文件名不能为空
                        if(schunk != null){   //分片数目
                            temFileName = schunk +"_"+name;   //分片的话文件名就是这个
                        }
                        File temFile = new File(uploadPath,temFileName);
                        if(!temFile.exists()){//断点续传
                            item.write(temFile);
                        }
                    }
                }
            }
            //文件合并
            if(schunk != null && schunk.intValue() == schunks.intValue()-1){
                File tempFile = new File(uploadPath,name);
                os = new BufferedOutputStream(new FileOutputStream(tempFile));

                for(int i=0 ;i<schunks;i++){
                    File file = new File(uploadPath,i+"_"+name);
                    while(!file.exists()){
                        Thread.sleep(100);
                    }
                    byte[] bytes = FileUtils.readFileToByteArray(file);
                    os.write(bytes);
                    os.flush();
                    file.delete();
                }
                os.flush();
            }

            //上传成功后将视频的路径存储在数据库中
            int i=name.lastIndexOf(".");
            String filePath = filepath+'/'+lastModifiedDate +name.substring(i);
            List<Course> courseList = courseService.selectTrue(book_name,menu_topic);
            int j = 0;
            if (courseList.size()!=0 ){
                j = courseService.updateCourse(book_name,menu_topic,null,filePath);
            }else {
                j = courseService.insertFile(book_name,menu_topic,filePath);
            }
            log.info("插入情况："+j);
            jsMindService.updateContent(book_name,menu_topic.split(":")[1]);
            response.getWriter().write("上传成功"+name);
        }finally {
            try{
                if(os != null){
                    os.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }


}
